part of _;

extension on ChatPage {
  Widget view_messages() {
    return Scrollbar(
      child: ListView.builder(
        controller: scrollController,
        reverse: true,
        primary: false,
        shrinkWrap: true,
        physics: BouncingScrollPhysics(),
        padding: EdgeInsets.only(top: 10),
        itemCount: messages.length,
        itemBuilder: (BuildContext context, int index) {
          return Container(
            padding: EdgeInsets.fromLTRB(10, 0, 10, 20),
            child: view_message(messages[index]),
          );
        },
      ),
    );
  }

  Widget view_pullLoading() {
    if (!isPullRefreshing) return YEmpty();
    return Card(
      margin: EdgeInsets.only(top: 10),
      elevation: 5,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(99)),
      child: Container(
        width: 30,
        height: 30,
        child: CircularProgressIndicator(strokeWidth: 3, backgroundColor: Colors.grey.shade200),
      ),
    );
  }

  Widget view_input() {
    Widget view_voice() {
      IconData getIcon() {
        switch (chatInputType) {
          case ChatInputType.Idle:
          case ChatInputType.Inputing:
          case ChatInputType.Face:
          case ChatInputType.Function:
            return Icons.keyboard_voice_outlined;
          case ChatInputType.Voice:
            return Icons.keyboard_alt_outlined;
        }
      }

      return YButton(
        width: 40,
        height: 40,
        padding: EdgeInsets.all(5),
        borderRadius: BorderRadius.circular(99),
        child: Container(
          padding: EdgeInsets.all(3),
          decoration: BoxDecoration(border: Border.all(color: YConfig.themeColor, width: 1.5), borderRadius: BorderRadius.circular(99)),
          child: Icon(getIcon(), size: 20, color: YConfig.themeColor),
        ),
        onTap: () async {
          yCloseInputMethod();
          switch (chatInputType) {
            case ChatInputType.Idle:
            case ChatInputType.Inputing:
            case ChatInputType.Face:
            case ChatInputType.Function:
              if (!(await Record().hasPermission())) {
                yToast("请授予录音权限");
                return;
              }
              setState(() => chatInputType = ChatInputType.Voice);
              break;
            case ChatInputType.Voice:
              setState(() => chatInputType = ChatInputType.Idle);
              break;
          }
        },
      );
    }

    Widget view_center() {
      Widget view_record() {
        return ChatRecordButton(
          onRecordFinish: (path, second) {
            addUploadMessages(
              [path],
              Enum_MessageType.Voice,
              onMessagePrepare: (messageModel) async => messageModel..content = json.encode({"url": messageModel.content, "second": second}),
              onSendContent: (content) async => json.encode({"url": content, "second": second}),
            );
          },
        );
      }

      Widget view_textfield() {
        return Container(
          margin: EdgeInsets.only(top: 5, bottom: 5),
          decoration: BoxDecoration(color: IFinal.Colors.pageBG, borderRadius: BorderRadius.circular(5)),
          alignment: Alignment.centerLeft,
          constraints: BoxConstraints(minHeight: 30),
          child: ExtendedTextField(
            controller: textEditingController,
            focusNode: focusNode,
            minLines: 1,
            maxLines: 5,
            style: TextStyle(fontSize: 14, height: 1.4),
            cursorWidth: 1,
            specialTextSpanBuilder: mySpecialTextSpanBuilder,
            decoration: InputDecoration(isCollapsed: true, contentPadding: EdgeInsets.all(5), border: InputBorder.none),
            onChanged: (value) => setState(() {}),
          ),
        );
      }

      return Expanded(child: chatInputType == ChatInputType.Voice ? view_record() : view_textfield());
    }

    Widget view_face() {
      IconData getIcon() {
        switch (chatInputType) {
          case ChatInputType.Idle:
          case ChatInputType.Inputing:
          case ChatInputType.Voice:
          case ChatInputType.Function:
            return Icons.emoji_emotions_outlined;
          case ChatInputType.Face:
            return Icons.keyboard_alt_outlined;
        }
      }

      return YButton(
        width: 40,
        height: 40,
        padding: EdgeInsets.all(5),
        borderRadius: BorderRadius.circular(99),
        child: Container(
          padding: EdgeInsets.all(3),
          decoration: BoxDecoration(border: Border.all(color: YConfig.themeColor, width: 1.5), borderRadius: BorderRadius.circular(99)),
          child: Icon(getIcon(), size: 20, color: YConfig.themeColor),
        ),
        onTap: () {
          yCloseInputMethod();
          switch (chatInputType) {
            case ChatInputType.Idle:
            case ChatInputType.Inputing:
            case ChatInputType.Voice:
            case ChatInputType.Function:
              yRun(() {
                setState(() => chatInputType = ChatInputType.Face);
                controller_scrollToBottom(checkIsBottom: true);
              }, delay: 150);
              break;
            case ChatInputType.Face:
              setState(() => chatInputType = ChatInputType.Idle);
              break;
          }
        },
      );
    }

    Widget view_sendOrFunction() {
      Widget view_function() {
        return YButton(
          width: 40,
          height: 40,
          padding: EdgeInsets.all(5),
          borderRadius: BorderRadius.circular(99),
          child: Container(
            padding: EdgeInsets.all(3),
            decoration: BoxDecoration(border: Border.all(color: YConfig.themeColor, width: 1.5), borderRadius: BorderRadius.circular(99)),
            child: Icon(Icons.add, size: 20, color: YConfig.themeColor),
          ),
          onTap: () {
            yCloseInputMethod();
            switch (chatInputType) {
              case ChatInputType.Idle:
              case ChatInputType.Inputing:
              case ChatInputType.Voice:
              case ChatInputType.Face:
                yRun(() {
                  setState(() => chatInputType = ChatInputType.Function);
                  controller_scrollToBottom(checkIsBottom: true);
                }, delay: 150);
                break;
              case ChatInputType.Function:
                setState(() => chatInputType = ChatInputType.Idle);
                break;
            }
          },
        );
      }

      Widget view_send() {
        return YButton(
          width: 50,
          height: 30,
          margin: EdgeInsets.only(right: 5, bottom: 5),
          borderRadius: BorderRadius.circular(5),
          decoration: BoxDecoration(gradient: IFinal.Colors.btnThemeGradient),
          child: Text("发送", style: TextStyle(fontSize: 12, color: Colors.white)),
          onTap: () {
            controller_sendMessage(
              Enum_MessageType.Text,
              textEditingController.text,
              onSendStart: (yimMessage) {
                textEditingController.clear();
                controller_addMessages(messages: [MessageModel.fromYIMMessage(yimMessage, true)]);
                controller_scrollToBottom();
              },
            );
          },
        );
      }

      return textEditingController.text.trim().isEmpty ? view_function() : view_send();
    }

    return Container(
      color: Colors.white,
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.end,
        children: [
          view_voice(),
          view_center(),
          view_face(),
          view_sendOrFunction(),
        ],
      ),
    );
  }

  Widget _view_bottom_container({required double height, required bool isShow, required Widget child}) {
    return !isShow
        ? YEmpty()
        : TweenAnimationBuilder<double>(
            tween: Tween(begin: height, end: 0),
            duration: const Duration(milliseconds: 300),
            curve: Curves.linearToEaseOut,
            builder: (context, value, _child) {
              return Transform.translate(
                offset: Offset(0, value),
                child: Container(
                  height: height - value,
                  child: child,
                ),
              );
            },
          );
  }

  Widget view_face() {
    return _view_bottom_container(
      height: 200,
      isShow: chatInputType == ChatInputType.Face,
      child: Stack(
        children: [
          GridView.builder(
            padding: EdgeInsets.all(10),
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 8, mainAxisSpacing: 10, crossAxisSpacing: 10, childAspectRatio: 1),
            itemCount: 99,
            itemBuilder: (context, index) {
              return YButton(
                isInk: true,
                padding: EdgeInsets.all(5),
                child: Image.asset("images/emoji/common/emoticon_${index + 1}.png"),
                onTap: () => controller_faceClick(index),
              );
            },
          ),
          Positioned(
            right: 5,
            bottom: 5,
            child: YButton(
              isInk: true,
              padding: EdgeInsets.fromLTRB(15, 10, 15, 10),
              borderRadius: BorderRadius.circular(5),
              decoration: BoxDecoration(color: Colors.white),
              child: Icon(Icons.backspace_rounded, size: 20, color: Colors.black),
              onTap: () => controller_faceDeleteClick(),
            ),
          ),
        ],
      ),
    );
  }

  Widget view_function() {
    final items = <Map<String, dynamic>>[
      {"title": "相册", "image": Icons.image_outlined},
      {"title": "拍摄", "image": Icons.camera_alt_rounded},
    ];

    return _view_bottom_container(
      height: 200,
      isShow: chatInputType == ChatInputType.Function,
      child: GridView.builder(
        padding: EdgeInsets.all(15),
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 4, mainAxisSpacing: 0, crossAxisSpacing: 0, childAspectRatio: 1),
        itemCount: items.length,
        itemBuilder: (context, index) {
          final item = items[index];
          return YButton(
            padding: EdgeInsets.only(top: 10, bottom: 10),
            child: Column(
              children: [
                Container(
                  padding: EdgeInsets.all(12),
                  decoration: BoxDecoration(color: Colors.grey.shade300, borderRadius: BorderRadius.circular(10)),
                  child: Icon(item["image"]),
                ),
                YExpanded(),
                Text(item["title"]),
              ],
            ),
            onTap: () => controller_functionClick(item),
          );
        },
      ),
    );
  }
}
